//
//  DetailTable.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/9/23.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "DetailTable.h"
#import "DetailCell.h"
#import "DetailModel.h"
#import "SDImageCache.h"
#import "UIImageView+WebCache.h"
#import "VoiceConverter.h"
#import "LoadingView.h"
@interface DetailTable()
{
    NSString *_warningUuid;
    NSMutableArray *_photosAr;
    UILabel *_timeLab;
    UIImageView *_imageView;
    NSInteger _soundClick;
    BOOL _isHiddenReplay;
    BOOL _isHiddenAdd;

}
@property(nonatomic,strong)AVAudioPlayer *audioPlayer;
@property(nonatomic,strong)NSString *warningUuid;

@end
@implementation DetailTable

-(instancetype)initWithFrame:(CGRect)frame withWarningUuid:(NSString *)warningUuid withState:(BOOL)isHidden withIsAdd:(BOOL)isAdd
{
    self = [super initWithFrame:frame];
    if (self) {
        [super initView];
        _isHiddenReplay=isHidden;
        _isHiddenAdd=isAdd;
        _soundClick=0;
        self.backgroundColor=[UIColor clearColor];
        self.warningUuid =warningUuid;
        [[LoadingView shareLoading]startAnimating];
        [CClass HttpRequestTask:YES withUrl:@"warninglist_orderContent" withData:@{@"warningUuid":self.warningUuid} notifyError:YES onSuccess:^(BaseModel *model) {
            NSDictionary *dataDic=model.B_data;
            [self setTableHeaderView:[self headViewWith:dataDic]];
            [[LoadingView shareLoading]stopAnimating];

        } onError:^(BaseModel *model) {
            [[LoadingView shareLoading]stopAnimating];

        }];
        [self setShowNoData:NO];
    self.backgroundColor =[UIColor clearColor];
    self.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.showsVerticalScrollIndicator =NO;
    [self registerCell:[DetailCell class] withModel:[DetailModel class]];
        _warningUuid=warningUuid;
    [self setDataWithUrl:@"warninglist_orderMessageBoard" andParam:@{@"warningUuid":_warningUuid} ];
    [self loadData];

    }
    
    return self;
    
}
- (void)willDetailView{
    [self setDataWithUrl:@"warninglist_orderMessageBoard" andParam:@{@"warningUuid":_warningUuid}];
    //详情请求
    [CClass HttpRequestTask:YES withUrl:@"warninglist_orderContent" withData:@{@"warningUuid":self.warningUuid} notifyError:YES onSuccess:^(BaseModel *model) {
        NSDictionary *dataDic=model.B_data;
        [self setTableHeaderView:[self headViewWith:dataDic]];
    } onError:^(BaseModel *model) {
        
    }];
    [self loadData];
    

}
- (UIView*)noDataView
{
    UIView *dataView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 200)];
    dataView.backgroundColor =[UIColor colorWithRed:255/255.0 green:255/255.0  blue:255/255.0  alpha:0.1];
    
    UIImage *logo = [UIImage imageNamed:@"Ico_home_noData"];
    UIImageView *logoView = [[UIImageView alloc] initWithFrame:CGRectMake((WindowWidth-logo.size.width)/2, 20, logo.size.width, logo.size.height)];
    [dataView addSubview:logoView];
    
    [logoView setImage:logo];
    
    
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(logoView.frame)+10, WindowWidth, 20)];
    [dataView addSubview:lbl];
    [lbl setText:@"没有内容"];
   lbl.textColor = C(@"989898");
    lbl.textAlignment=NSTextAlignmentCenter;
    [lbl setFont:F(16)];
    return dataView;
    
}
- (void)reloadData
{
    
    if(self.mainData.count==0)
    {
        [self setTableFooterView:[self noDataView]];
        
    }else
    {
        [self setTableFooterView:nil];
        
    }
    
    [super reloadData];
    
}
- (void)stopAudioPlayer
{
    [self.audioPlayer stop];
    self.audioPlayer.currentTime = 0;
    [_imageView stopAnimating];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else
    {
        return self.mainData.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 35;
    }else
    {
        DetailModel *model = [self.mainData objectAtIndex:indexPath.row];
        CGSize labelsize = CGSizeZero;
        //    //字体为空时候，有图片的时候
        if(([model.P_describe isKindOfClass:[NSNull class]]||[model.P_describe isEqualToString:@""])&&(![model.P_image isEqualToString:@""]||![model.P_image isKindOfClass:[NSNull class]]))
        {
            return 70+50;
            
        }else
            //图片为空时候，有字体的时候
            if((![model.P_describe isKindOfClass:[NSNull class]]||![model.P_describe isEqualToString:@""])&&([model.P_image isEqualToString:@""]||[model.P_image isKindOfClass:[NSNull class]]))
            {
                
                labelsize = [model.P_describe sizeWithFont:F(12) constrainedToSize:CGSizeMake(WindowWidth-105, 900)];
                return MAX(labelsize.height+40+40, 70+40);
                
            }else
            {
                //有图片时候，有字体的时候
                
                labelsize = [model.P_describe sizeWithFont:F(12) constrainedToSize:CGSizeMake(WindowWidth-105, 900)];
                
                return MAX(labelsize.height+32+50+12+40,70+40);
                
            }
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    DetailCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"]; //出列可重用的
    if (cell == nil) {
        cell = [[DetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        UILabel*numMessgeLab =[[UILabel alloc]initWithFrame:CGRectMake(25, 0, 100, 35)];
        numMessgeLab.tag=3;
        numMessgeLab.font=FF(14);
        numMessgeLab.textColor=FontColor;
        numMessgeLab.userInteractionEnabled=YES;
        [cell.contentView addSubview:numMessgeLab];
        
        UILabel *replyLab =[[UILabel alloc]initWithFrame:CGRectMake(WindowWidth-100-15, 0, 100, 35)];
        replyLab.textColor=MainColor;
        replyLab.font=FF(14);
        replyLab.tag=4;
        replyLab.userInteractionEnabled=YES;
        replyLab.textAlignment=NSTextAlignmentRight;
        [cell.contentView addSubview:replyLab];
        
    }

    if (indexPath.section==0) {
        UILabel *numLab=[cell.contentView viewWithTag:3];
        numLab.text=@"补充描述";
        UILabel *replyLab=[cell.contentView viewWithTag:4];
        replyLab.text=@"回复";
            if (_isHiddenReplay==YES) {
                    replyLab.hidden=YES;
                }else
                {
                    replyLab.hidden=NO;
                }
        [replyLab bk_whenTapped:^{
            [self.audioPlayer stop];
            self.audioPlayer.currentTime = 0;
            [_imageView stopAnimating];
            if (self.gotoReply) {
                self.gotoReply(self.warningUuid);
            }
        }];


    }else
    {
 
       cell.backgroundColor=[UIColor whiteColor];
        DetailModel *model = [self.mainData objectAtIndex:indexPath.row];
        [cell setModel:model];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
  
    return cell;

}
- (UIView*)headViewWith:(NSDictionary *)dict
{
    _photosAr=[[NSMutableArray alloc]init];
    NSString*urlString =[CClass getCacheData:qnDomain];
    UIView *bgView =[[UIScrollView alloc]initWithFrame:CGRectMake(WindowWidth, 10, WindowWidth,WindowHeight-102-10)];
    bgView.backgroundColor =BackColor;
    UIView* contextView=[[UIView alloc]init];
    [bgView addSubview:contextView];
    contextView.frame =CGRectMake(0, 0, WindowWidth, 40);
    contextView.backgroundColor =[UIColor whiteColor];
#pragma mark设备
    NSString *machineName;
    NSString *typeNm;
    
    UILabel*equipmentLab=[[UILabel alloc]init];
    [contextView addSubview:equipmentLab];
    equipmentLab.text =@"报修设备";
    equipmentLab.textColor =FontColor;
    equipmentLab.font =FF(14);
    UILabel*nameLab=[[UILabel alloc]init];
    [contextView addSubview:nameLab];
    
    nameLab.text =[NSString stringWithFormat:@"%@\n%@",typeNm,machineName];
    nameLab.textColor =MainColor;
    nameLab.font =FF(14);
    nameLab.numberOfLines=0;
    nameLab.userInteractionEnabled=YES;
    
    
    if([F_NSpace([dict objectForKey:@"machineName"]) isEqualToString:@""]&&[F_NSpace([dict objectForKey:@"typeNm"]) isEqualToString:@""]){
        
        contextView.frame =CGRectMake(0, 0, WindowWidth, 40);
        equipmentLab.frame=CGRectMake(25, 15, 65, 15);
        nameLab.frame=CGRectMake(CGRectGetMaxX(equipmentLab.frame), 15, WindowWidth-CGRectGetMaxX(equipmentLab.frame)-10, 15);
        if(_isHiddenAdd==YES)
        {
            nameLab.text=@"未添加";
            nameLab.textColor=FontColor;
            
        }else
        {
            nameLab.text=@"补充         ";
            [nameLab bk_whenTapped:^{
                [self.audioPlayer stop];
                self.audioPlayer.currentTime = 0;
                [_imageView stopAnimating];
                NSMutableDictionary *datdaDic=[[NSMutableDictionary alloc]init];
                [datdaDic setObject:self.warningUuid forKey:@"warningUuid"];
                if (self.gotoAddDetail) {
                    self.gotoAddDetail(self.warningUuid,[dict objectForKey:@"instUuid"]);
                }
                
            }];
        }
       
    }else
    {
        
        if ([F_NSpace([dict objectForKey:@"machineName"]) isEqualToString:@""]) {
            typeNm=[dict objectForKey:@"typeNm"];
            CGSize typeNmsize = [typeNm sizeWithFont:FF(14) constrainedToSize:CGSizeMake(WindowWidth-25-65-10, 900)];
            contextView.frame =CGRectMake(0, 0, WindowWidth,typeNmsize.height+15+40);
            equipmentLab.frame=CGRectMake(25, 15, 65, 15);
            nameLab.frame=CGRectMake(CGRectGetMaxX(equipmentLab.frame), 15, WindowWidth-CGRectGetMaxX(equipmentLab.frame)-10, typeNmsize.height);
            nameLab.text =[NSString stringWithFormat:@"%@",typeNm];
            [nameLab bk_whenTapped:^{
                [self.audioPlayer stop];
                self.audioPlayer.currentTime = 0;
                [_imageView stopAnimating];
                if(self.gotoDeviceDetail)
                {
                    self.gotoDeviceDetail([dict objectForKey:@"machine_uuid"]);
                }
                
            }];
            
        }else if ([F_NSpace([dict objectForKey:@"typeNm"]) isEqualToString:@""])
        {
            machineName=[dict objectForKey:@"machineName"];
            
            CGSize namesize = [machineName sizeWithFont:FF(14) constrainedToSize:CGSizeMake(WindowWidth-25-65-10, 900)];
            contextView.frame =CGRectMake(0, 0, WindowWidth,namesize.height+15+40);
            equipmentLab.frame=CGRectMake(25, 15, 65, 15);
            nameLab.frame=CGRectMake(CGRectGetMaxX(equipmentLab.frame), 15, WindowWidth-CGRectGetMaxX(equipmentLab.frame)-10, namesize.height);
            nameLab.text =[NSString stringWithFormat:@"%@",machineName];
            [nameLab bk_whenTapped:^{
                [self.audioPlayer stop];
                self.audioPlayer.currentTime = 0;
                [_imageView stopAnimating];
                if (self.gotoDeviceDetail) {
                    self.gotoDeviceDetail([dict objectForKey:@"machine_uuid"]);
                }
                
            }];
        }else
        {
            machineName=[dict objectForKey:@"machineName"];
            typeNm=[dict objectForKey:@"typeNm"];
            
            CGSize namesize = [machineName sizeWithFont:FF(14) constrainedToSize:CGSizeMake(WindowWidth-25-65-10, 900)];
            CGSize typesize = [typeNm sizeWithFont:FF(14) constrainedToSize:CGSizeMake(WindowWidth-25-65-10, 900)];
            contextView.frame =CGRectMake(0, 0, WindowWidth,namesize.height+15+40+typesize.height);
            equipmentLab.frame=CGRectMake(25, 15, 65, 15);
            nameLab.frame=CGRectMake(CGRectGetMaxX(equipmentLab.frame), 15, WindowWidth-CGRectGetMaxX(equipmentLab.frame)-10, namesize.height+typesize.height);
            nameLab.text =[NSString stringWithFormat:@"%@\n%@",typeNm,machineName];
            [nameLab bk_whenTapped:^{
                [self.audioPlayer stop];
                self.audioPlayer.currentTime = 0;
                [_imageView stopAnimating];
                if(self.gotoDeviceDetail)
                {
                    self.gotoDeviceDetail([dict objectForKey:@"machine_uuid"]);
                }
                
            }];
            
        }
    }
    
    
    UILabel*lab2=[[UILabel alloc]initWithFrame:CGRectMake(25, CGRectGetMaxY(nameLab.frame)+15, 65, 15)];
    [contextView addSubview:lab2];
    lab2.text =@"报修内容";
    lab2.textColor =FontColor;
    lab2.font= FF(14);
    
#pragma mark文字
    
    CGFloat describeHeight ;
    if ([F_NSpace([dict objectForKey:@"describe"]) isEqualToString:@""]) {
        describeHeight=0;
    }else
    {
        
       CGSize describeSize = [[dict objectForKey:@"describe"] sizeWithFont:F(11) constrainedToSize:CGSizeMake(WindowWidth-50, 900)];
        describeHeight=describeSize.height;
    }
    
    UILabel*describeLab=[[UILabel alloc]initWithFrame:CGRectMake(25,CGRectGetMaxY(lab2.frame)+10, WindowWidth-50,describeHeight)];
    [contextView addSubview:describeLab];
    
    if ([F_NSpace([dict objectForKey:@"describe"]) isEqualToString:@""]) {
        
        describeLab.text =@"";
    }else
    {
        describeLab.text =[dict objectForKey:@"describe"];
        
    }
    describeLab.textColor =LightFontColor;
    describeLab.font= F(11);
    describeLab.numberOfLines=0;
    CGFloat soundBtnOrgtY;
    
#pragma mark语音
    if([F_NSpace([dict objectForKey:@"audioAmr"]) isEqualToString:@""])
    {
        soundBtnOrgtY=CGRectGetMaxY(describeLab.frame);
    }else
    {
        soundBtnOrgtY=CGRectGetMaxY(describeLab.frame)+35;
//        contextView.frame=CGRectMake(0, 0, WindowWidth, CGRectGetMaxY(contextView.frame)+40);
        //语音
        //1.音频文件的url路径
        NSURL *voiceUrl =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,[dict objectForKey:@"audioAmr"]]];
        NSData * audioData = [NSData dataWithContentsOfURL:voiceUrl];
        
        //将数据保存到本地指定位置
        NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@.amr", docDirPath , @"temp"];
        [audioData writeToFile:filePath atomically:YES];
        
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if([fileManager removeItemAtPath:filePath error:nil])
        {
            echo(@"删除以前的arm文件");
        }else
        {
            [audioData writeToFile:filePath atomically:YES];
            
        }
        //转码之后的WAV文件
        NSString *playPath = [NSString stringWithFormat:@"%@/%@.wav", docDirPath , @"play"];
        if([fileManager removeItemAtPath:filePath error:nil])
        {
            echo(@"删除以前的wav文件");
        }else
        {
            [audioData writeToFile:filePath atomically:YES];
            
        }
        
        [VoiceConverter ConvertAmrToWav:filePath wavSavePath:playPath];
        
        
        //播放录音
        NSError *error;
        AVAudioSession *seesion= [AVAudioSession sharedInstance];
        //混音播放
        [seesion setCategory:AVAudioSessionCategoryPlayback error:nil];
        [seesion setActive:YES error:nil];
        
        //播放本地音乐
        NSURL *fileURL = [NSURL fileURLWithPath:playPath];
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
        UIImageView *soudBtn=[[UIImageView alloc]initWithFrame:CGRectMake(25, CGRectGetMaxY(describeLab.frame)+5, 200, 30)];
        soudBtn.userInteractionEnabled=YES;
        soudBtn.image=[UIImage imageNamed:@"Ico_home_ soundBg"];
        [contextView addSubview:soudBtn];
        
        _timeLab =[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(soudBtn.frame)+5, CGRectGetMaxY(describeLab.frame)+10, contextView.bounds.size.width-CGRectGetMaxX(soudBtn.frame)-20, 16)];
        _timeLab.font =FF(12);
        _timeLab.hidden=NO;
        _timeLab.text =[NSString stringWithFormat:@"%ld s",(long)self.audioPlayer .duration];
        [contextView addSubview:_timeLab];
        
        _timeLab.textColor =LightFontColor;
        
        //定义数组，存放所有图片对象
        NSArray *images=[NSArray arrayWithObjects:[UIImage imageNamed:@"Ico_home_ sonic1"],[UIImage imageNamed:@"Ico_home_ sonic2"],[UIImage imageNamed:@"Ico_home_ sonic3"],nil];
        _imageView =[[UIImageView alloc]initWithFrame:CGRectMake(15, 0, 30, 30)];
        _imageView.userInteractionEnabled=YES;
        _imageView.image =[UIImage imageNamed:@"Ico_home_ sonic3"];
        //imageView的动画图片是数组images
        _imageView.animationImages = images;
        //按照原始比例缩放图片，保持纵横比
        _imageView.contentMode = UIViewContentModeScaleAspectFit;
        //切换动作的时间3秒，来控制图像显示的速度有多快，
        _imageView.animationDuration = 3;
        //动画的重复次数，想让它无限循环就赋成0
        _imageView.animationRepeatCount = 0;
        //添加控件
        [soudBtn addSubview:_imageView];
        
        [soudBtn bk_whenTapped:^{
            
            _soundClick++;
            if (_soundClick%2==0) {
                [self.audioPlayer stop];
                self.audioPlayer.currentTime = 0;
                [_imageView stopAnimating];
                
            }else{
                if (self.audioPlayer  == nil)
                {
                    echo(([NSString stringWithFormat:@"ERror creating player: %@", [error description]]));

                }else{
                    //准备播放
                    [self.audioPlayer  prepareToPlay];
                    //播放
                    [self.audioPlayer  play];
                    
                    //开始动画
                    [_imageView startAnimating];
                    
                    __block  NSInteger duration = (NSInteger)self.audioPlayer .duration;
                    NSTimeInterval period = 1.0; //设置时间间隔
                    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
                    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
                    dispatch_source_set_event_handler(_timer, ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                        });
                        if (duration -- <= 0 ) {
                            dispatch_source_cancel(_timer);
                            dispatch_async(dispatch_get_main_queue(), ^{
                                
                                //关闭动画
                                [_imageView stopAnimating];
                            });
                        }
                    });
                    dispatch_resume(_timer);
                    
                }
                
            }
            
        }];
        
    }
#pragma mark语音翻译
  
    
    UILabel*translatorLab=[[UILabel alloc]init];
    [contextView addSubview:translatorLab];
    
    CGSize translatorSize ;
    if ([F_NSpace([dict objectForKey:@"audio_translator"]) isEqualToString:@""]) {
        translatorSize.height=0;
        translatorLab.text =@"";

    }else
    {
        NSString *string=[NSString stringWithFormat:@"(%@)",[dict objectForKey:@"audio_translator"]];
        translatorSize = [[dict objectForKey:@"audio_translator"] sizeWithFont:F(11) constrainedToSize:CGSizeMake(WindowWidth-50, 900)];
        translatorLab.text =string;

    }
    translatorLab.frame=CGRectMake(25,soundBtnOrgtY+5, WindowWidth-50,translatorSize.height);
    translatorLab.textColor =LightFontColor;
    translatorLab.font= F(11);
    translatorLab.numberOfLines=0;

    CGFloat translatororighY=CGRectGetMaxY(translatorLab.frame); //soundBtnOrgtY+translatorSize.height+10;


    CGFloat width =(WindowWidth-30-50)/3;
//    CGFloat soundOrgtY=CGRectGetMaxY(translatorLab.frame)+5; //CGRectGetMaxY(contextView.frame);
    
    _photosAr=[[NSMutableArray alloc]init];
    CGFloat imgOrgtY;

    if ([F_NSpace([dict objectForKey:@"image"]) isEqualToString:@""]&&([F_NSpace([dict objectForKey:@"video"]) isEqualToString:@""])) {
        
        imgOrgtY=10;
        
    }else if ([F_NSpace([dict objectForKey:@"image"]) isEqualToString:@""]||([F_NSpace([dict objectForKey:@"video"]) isEqualToString:@""])) {
        imgOrgtY=width+15+15;
//        CGFloat orighY=CGRectGetMaxY(contextView.frame)+width+30;
//        contextView.frame=CGRectMake(0, 0, WindowWidth, orighY);
        if ([F_NSpace([dict objectForKey:@"video"]) isEqualToString:@""]) {
#pragma mark只有图片
            NSString *str =[dict objectForKey:@"image"];
            
            NSArray *array = [str componentsSeparatedByString:@","];
            for (int i=0; i<array.count; i++) {
                UIImageView *img =[[UIImageView alloc]initWithFrame:CGRectMake(25+(width+15)*i, 15+translatororighY, width, width)];
                img.userInteractionEnabled=YES;
                img.tag=i;
                NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,[array objectAtIndex:i]]];
                [img sd_setImageWithURL:url];
                
                NSDictionary *imgDict=[NSDictionary dictionaryWithObjectsAndKeys:@1,@"type",url,@"img", nil];
                [_photosAr addObject:imgDict];
                [contextView addSubview:img];
                img.userInteractionEnabled=YES;
                
                [img bk_whenTapped:^{
                    [self.audioPlayer stop];
                    self.audioPlayer.currentTime = 0;
                    [_imageView stopAnimating];
                    NSMutableDictionary *imgDic=[[NSMutableDictionary alloc]init];
                    NSString *num=[NSString stringWithFormat:@"%d",i];
                    [imgDic setObject:num forKey:@"imgTag"];
                    [imgDic setObject:_photosAr forKey:@"phoneAr"];
                    
                    //预览图片
                    if (self.clickImg) {
                        self.clickImg(imgDic);
                    }
                    
                    
                }];
            }
            
        }else if ([F_NSpace([dict objectForKey:@"image"]) isEqualToString:@""])
        {
#pragma mark只有视频
            UIImageView *img =[[UIImageView alloc]initWithFrame:CGRectMake(25, 15+translatororighY, width, width)];
            img.userInteractionEnabled=YES;
            [contextView addSubview:img];
            
            NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,[dict objectForKey:@"video"]]];
            
            UIImage *image = [UIImage imageNamed:@"Ico_home_play"];
            UIImageView* videoImageView = [[UIImageView alloc] initWithFrame:CGRectMake((img.frame.size.width-image.size.width)/2, (img.frame.size.height-image.size.height)/2, image.size.width, image.size.height)];
            videoImageView.contentMode = UIViewContentModeScaleAspectFill;
            videoImageView.image=image;
            [img addSubview:videoImageView];
            [self centerFrameImageWithVideoURL:url completion:^(UIImage *image) {
                img.image= image;
            }];
#pragma mark播放视频
            NSDictionary *imgDict=[NSDictionary dictionaryWithObjectsAndKeys:@2,@"type",url,@"img", nil];
            [_photosAr addObject:imgDict];
            [img bk_whenTapped:^{
                
                [self.audioPlayer stop];
                self.audioPlayer.currentTime = 0;
                [_imageView stopAnimating];
                NSMutableDictionary *imgDic=[[NSMutableDictionary alloc]init];
                NSString *num=[NSString stringWithFormat:@"%d",0];
                [imgDic setObject:num forKey:@"imgTag"];
                [imgDic setObject:_photosAr forKey:@"phoneAr"];
                
                //预览图片
                if (self.clickImg) {
                    self.clickImg(imgDic);
                }
                
            }];
        }
        
    }else{
#pragma mark有视频和图片
        NSString *str =[dict objectForKey:@"image"];
//        
        NSArray *array = [str componentsSeparatedByString:@","];
        if(array.count+1==4)
        {
            imgOrgtY=(width+15)*2+15;

        }else
        {
            imgOrgtY=width+15+15;

        }
        for (int i=0; i<array.count+1; i++) {
            UIImageView *img =[[UIImageView alloc]initWithFrame:CGRectMake(25+(width+15)*(i%3), 15+translatororighY+(width+15)*(i/3), width, width)];
            img.userInteractionEnabled=YES;
            img.tag=i;
            [contextView addSubview:img];
            if(i<array.count)
            {
                NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,[array objectAtIndex:i]]];
                [img sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@""]];
                
                NSDictionary *imgDict=[NSDictionary dictionaryWithObjectsAndKeys:@1,@"type",url,@"img", nil];
                [_photosAr addObject:imgDict];
                img.userInteractionEnabled=YES;
            }
            if(i==array.count)
            {
                
                NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,[dict objectForKey:@"video"]]];
                
                UIImage *image = [UIImage imageNamed:@"Ico_home_play"];
                UIImageView* videoImageView = [[UIImageView alloc] initWithFrame:CGRectMake((img.frame.size.width-image.size.width)/2, (img.frame.size.height-image.size.height)/2, image.size.width, image.size.height)];
                videoImageView.contentMode = UIViewContentModeScaleAspectFill;
                videoImageView.image=image;
                [img addSubview:videoImageView];
                [self centerFrameImageWithVideoURL:url completion:^(UIImage *image) {
                    img.image= image;
                }];
                NSDictionary *imgDict=[NSDictionary dictionaryWithObjectsAndKeys:@2,@"type",url,@"img", nil];
                [_photosAr addObject:imgDict];
                
                
            }
            [img bk_whenTapped:^{
                [self.audioPlayer stop];
                self.audioPlayer.currentTime = 0;
                [_imageView stopAnimating];
                
                NSMutableDictionary *imgDic=[[NSMutableDictionary alloc]init];
                NSString *num=[NSString stringWithFormat:@"%d",i];
                [imgDic setObject:num forKey:@"imgTag"];
                [imgDic setObject:_photosAr forKey:@"phoneAr"];
                
                //预览图片
                if (self.clickImg) {
                    self.clickImg(imgDic);
                }
                
            }];
        }
    }
    contextView.frame=CGRectMake(0, 0, WindowWidth, translatororighY+imgOrgtY);


    
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(contextView.frame), WindowWidth, 10)];
    backView.backgroundColor=BackColor;
    [bgView addSubview:backView];
    UIView* footView =[[UIView alloc]init];
    CGFloat height = 15*5;
    
    footView.frame =CGRectMake(0, CGRectGetMaxY(backView.frame), WindowWidth, height);
    footView.backgroundColor =[UIColor whiteColor];
    [bgView addSubview:footView];
    UILabel*lab=[[UILabel alloc]initWithFrame:CGRectMake(25, 15, 65, 15)];
    [footView addSubview:lab];
    lab.text =@"报修单号";
    lab.textColor =FontColor;
    lab.font =FF(14);
    
    UILabel*numLab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lab.frame), 15, WindowWidth-CGRectGetMaxX(lab.frame), 15)];
    [footView addSubview:numLab];
    if ([F_NSpace([dict objectForKey:@"order_number"]) isEqualToString:@""])
    {
        numLab.text =[dict objectForKey:@""];
        
    }else
    {
        numLab.text =[dict objectForKey:@"order_number"];
        
    }
    numLab.textColor =LightFontColor;
    numLab.font =FF(14);
    
#pragma mark     报修机构
    NSString *inst;
    if ([F_NSpace([dict objectForKey:@"instName"]) isEqualToString:@""])
 {
     inst=@"";
    }else
    {
        inst=[dict objectForKey:@"instName"];

    }
    CGSize labelsize = [inst sizeWithFont:FF(14) constrainedToSize:CGSizeMake(WindowWidth-15-65, 900)];
    footView.frame =CGRectMake(0, CGRectGetMaxY(contextView.frame)+10, WindowWidth, labelsize.height+height+20+5);
    
    UILabel*lab4=[[UILabel alloc]initWithFrame:CGRectMake(25, 45, 65, 15)];
    [footView addSubview:lab4];
    lab4.text =@"报修机构";
    lab4.textColor =FontColor;
    lab4.font =FF(14);
    
    UILabel*addressLab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lab4.frame), 45, WindowWidth-CGRectGetMaxX(lab4.frame), labelsize.height)];
    [footView addSubview:addressLab];
    
    addressLab.textColor =MainColor;
    addressLab.font =FF(14);
    addressLab.numberOfLines=0;
    addressLab.userInteractionEnabled=YES;
    addressLab.text =inst;
    [addressLab bk_whenTapped:^{
        [self.audioPlayer stop];
        self.audioPlayer.currentTime = 0;
        [_imageView stopAnimating];
        ///报修机构
        if (self.gotoMap) {
            NSMutableDictionary *dataDic=[[NSMutableDictionary alloc]init];
            [dataDic setObject:[dict objectForKey:@"latitude"] forKey:@"latitude"];
            [dataDic setObject:[dict objectForKey:@"longitude"]forKey:@"longitude"];
            [dataDic setObject:inst forKey:@"addressName"];

            self.gotoMap(dataDic);
            
        }
    }];
#pragma mark采购明细 通过判断确认的单
    if ([dict objectForKey:@"purchase_count_confirmed"]==nil) {
        footView.frame=CGRectMake(0, CGRectGetMaxY(backView.frame), WindowWidth, 45+labelsize.height+15);

    }else
    {
        if ([[NSString stringWithFormat:@"%@",[dict objectForKey:@"purchase_count_confirmed"]] isEqualToString:@"0"])
        {
            footView.frame=CGRectMake(0, CGRectGetMaxY(backView.frame), WindowWidth, 45+labelsize.height+15);
            
        }else
        {
            
            UILabel*sampleLab=[[UILabel alloc]initWithFrame:CGRectMake(25, CGRectGetMaxY(addressLab.frame)+15, 65, 15)];
            [footView addSubview:sampleLab];
            sampleLab.text =@"采购明细";
            sampleLab.textColor =FontColor;
            sampleLab.font =FF(14);
            UIButton*sampleBtn=[UIButton buttonWithType:UIButtonTypeCustom];
            sampleBtn.frame=CGRectMake(CGRectGetMaxX(sampleLab.frame), CGRectGetMaxY(addressLab.frame)+12.5, 80, 20);
            [sampleBtn setTitle:@"查看明细" forState:UIControlStateNormal];
            sampleBtn.titleLabel.font=FF(14);
            sampleBtn.layer.masksToBounds=YES;
            sampleBtn.layer.cornerRadius=3;
            sampleBtn.layer.borderColor=MainColor.CGColor;
            sampleBtn.layer.borderWidth=1;
            [sampleBtn setTitleColor:MainColor forState:UIControlStateNormal];
            [footView addSubview:sampleBtn];
            [sampleBtn bk_addEventHandler:^(id sender) {
                
                if (self.gotoSampleDetail) {
                    self.gotoSampleDetail(self.warningUuid);
                }
                
            } forControlEvents:UIControlEventTouchUpInside];
            
            
            footView.frame=CGRectMake(0, CGRectGetMaxY(backView.frame), WindowWidth, 45+labelsize.height+15+15*2);
            
            
        }

    }
   

    UIView *backView1=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(footView.frame), WindowWidth, 10)];
    backView1.backgroundColor=BackColor;
    [bgView addSubview:backView1];
    
    bgView.frame=CGRectMake(0, 0, WindowWidth,CGRectGetMaxY(backView1.frame));
    return bgView;
    
  

}
#pragma mark 获取视频首帧图片
-(UIImage*)cutMovieImageWith:(NSURL*)urlString{
    //创建URL
    NSURL *url=urlString;
    //根据url创建AVURLAsset
    AVURLAsset *urlAsset=[AVURLAsset assetWithURL:url];
    //根据AVURLAsset创建AVAssetImageGenerator
    AVAssetImageGenerator *imageGenerator=[AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    /*截图
     * requestTime:缩略图创建时间
     * actualTime:缩略图实际生成的时间
     */
    NSError *error=nil;
    CMTime time=CMTimeMakeWithSeconds(1, 1);//CMTime是表示电影时间信息的结构体，第一个参数表示是视频第几秒，第二个参数表示每秒帧数.(如果要活的某一秒的第几帧可以使用CMTimeMake方法)
    CMTime actualTime;
    CGImageRef cgImage= [imageGenerator copyCGImageAtTime:time actualTime:&actualTime error:&error];
    if(error){
        //        DSLog(@"截取视频缩略图时发生错误，错误信息：%@",error.localizedDescription);
        return nil;
    }
    CMTimeShow(actualTime);
    UIImage *cutImage=[UIImage imageWithCGImage:cgImage];//转化为UIImage
    return cutImage;
}
#pragma mark  异步获取帧图片，可以一次获取多帧图片
- (void)centerFrameImageWithVideoURL:(NSURL *)videoURL completion:(void (^)(UIImage *image))completion {
    // AVAssetImageGenerator
    AVAsset *asset = [AVAsset assetWithURL:videoURL];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    
    // calculate the midpoint time of video
    Float64 duration = CMTimeGetSeconds([asset duration]);
    // 取某个帧的时间，参数一表示哪个时间（秒），参数二表示每秒多少帧
    // 通常来说，600是一个常用的公共参数，苹果有说明:
    // 24 frames per second (fps) for film, 30 fps for NTSC (used for TV in North America and
    // Japan), and 25 fps for PAL (used for TV in Europe).
    // Using a timescale of 600, you can exactly represent any number of frames in these systems
    CMTime midpoint = CMTimeMakeWithSeconds(duration / 2.0, 600);
    
    // 异步获取多帧图片
    NSValue *midTime = [NSValue valueWithCMTime:midpoint];
    [imageGenerator generateCGImagesAsynchronouslyForTimes:@[midTime] completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        if (result == AVAssetImageGeneratorSucceeded && image != NULL) {
            UIImage *centerFrameImage = [[UIImage alloc] initWithCGImage:image];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(centerFrameImage);
                }
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(nil);
                }
            });
        }
    }];
}
@end
